package com.rpoonolly.simplegame.renderer;

import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Map;

import com.rpoonolly.simplegame.Config;
import com.rpoonolly.simplegame.animation.TexturedDynamicEntity;
import com.rpoonolly.simplegame.core.aabb.AABBEntity;
import com.rpoonolly.simplegame.core.aabb.DynamicAABBEntity;
import com.rpoonolly.simplegame.core.aabb.EntityGameMap;
import com.rpoonolly.simplegame.textures.TextureLoader;

public class SwingEntityRenderer extends SimpleSwingRenderer {
	protected EntityGameMap<AABBEntity> gameMap;
	private TextureLoader textureLoader;
	private Map<String, List<AABBEntity>> entities;

	public SwingEntityRenderer(EntityGameMap<AABBEntity> gameMap, TextureLoader textureLoader) {
		this.gameMap = gameMap;
		this.entities = gameMap.getEntities();
		this.textureLoader = textureLoader;
	}
	
	@Override
	public void render() {
		DynamicAABBEntity player = (DynamicAABBEntity) entities.get(Config.ENT_GRP_PLAYER).get(0);
		setFocalPoint(player);
		//clearScreen();
		
		for(List<AABBEntity> group : entities.values())
			render(group);
	}

	public void render(List<AABBEntity> entities) {
		for( AABBEntity entity : entities)
			render(entity);
	}
	
	public void render(AABBEntity entity) {
		if (graphics == null) return;
		
		double xcoord, ycoord;
		xcoord = entity.getX() - focalPoint.x + (windowWidth / 2);
		ycoord = -1 * (entity.getY() + entity.getHeight() - focalPoint.y - (windowHeight / 2));
		
		if (xcoord + entity.getWidth() < 0 || ycoord + entity.getHeight() < 0
				|| xcoord > windowWidth || ycoord > windowHeight)
			return;
		
		entityRenderWrapper(entity, (int) xcoord, (int) ycoord, (int) entity.getWidth(), (int) entity.getHeight());
	}
	
	protected void entityRenderWrapper(AABBEntity entity, int x, int y, int width, int height) {
		if (entity instanceof TexturedDynamicEntity) 
			renderTexturedDynamicEntity((TexturedDynamicEntity) entity, x, y);
	}
	
	private void renderTexturedDynamicEntity(TexturedDynamicEntity entity, int x, int y) {
		BufferedImage texture = textureLoader.loadTexture(entity.getCurrentTexture());
		graphics.drawImage(texture, x, y, texture.getWidth(), texture.getHeight(), null);
	}
}
